<?php

namespace App\Models;


use App\Service\Base\Model;
use Illuminate\Support\Facades\DB;

class Course extends Model
{

    // 广告管理
    protected $table = 'course';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'auth_id'];

    // {"id":"自编号","uid":"用户ID","auth_id":"认证ID","name":"认证名称","times":"课时","start_time":"开始时间","end_time":"结束时间","city":"城市","address":"所在地","description":"认证描述","status":"状态（1-正常，-1删除）","ctime":"注册时间","mtime":"更新时间"}


    // array ( 'id' => '$this->getData("id")', 'uid' => '$this->getData("uid")', 'auth_id' => '$this->getData("auth_id")', 'name' => '$this->getData("name")', 'times' => '$this->getData("times")', 'start_time' => '$this->getData("start_time")', 'end_time' => '$this->getData("end_time")', 'city' => '$this->getData("city")', 'address' => '$this->getData("address")', 'description' => '$this->getData("description")', 'status' => '$this->getData("status")', 'ctime' => '$this->getData("ctime")', 'mtime' => '$this->getData("mtime")', )


    // $id = $this->getData("id"); $uid = $this->getData("uid"); $auth_id = $this->getData("auth_id"); $name = $this->getData("name"); $times = $this->getData("times"); $start_time = $this->getData("start_time"); $end_time = $this->getData("end_time"); $city = $this->getData("city"); $address = $this->getData("address"); $description = $this->getData("description"); $status = $this->getData("status"); $ctime = $this->getData("ctime"); $mtime = $this->getData("mtime");


    // 添加课程 同时添加周期 和 课程学生
    public function oneAdd($data = [])
    {
        // 上课周期
        // 课程学生
        $cycle   = $data['cycle'] ?? [];
        $student = $data['student'] ?? [];
        unset($data['cycle'], $data['student']);

        // 验证信息
        $rules  = $this->fieldRule();
        $result = $this->validator($data, $rules, ['id' => '修改的用户编号']);
        if($result === false){
            return false;
        }

        // 模型 和 查询
        $studentDb = new CourseStudent();
        $cycleDb   = new CourseCycle();
        $this->fill($data);

        // 保存信息
        DB::beginTransaction();
        try{
            // 保存
            $result    = $this->save();
            $course_id = $this->id;

            // 保存学生
            if($student){
                $all = [];
                foreach($student as $item){
                    $all[] = ['course_id' => $course_id, 'student_id' => $item];
                }
                $studentDb->insert($all);
            }

            // 保存课程周期
            if($cycle){
                $all = [];
                foreach($cycle as $item){
                    $all[] = ['course_id' => $course_id, 'cycle' => $item['cycle'], 'number' => $item['number'], 'hour' => $item['hour'], 'minute' => $item['minute']];
                }
                $cycleDb->insert($all);
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($data);

        return $this->id;
    }

    // 修改课程
    public function oneEdit($where, $data)
    {
        // 上课周期
        // 课程学生
        $cycle   = $data['cycle'] ?? [];
        $student = $data['student'] ?? [];
        unset($data['cycle'], $data['student']);

        // 验证信息
        $rules  = $this->fieldRule();
        $result = $this->validator($data, $rules, ['id' => '修改的用户编号']);
        if($result === false){
            return false;
        }

        $info = $this->where($where)->first();  // ->recycle()
        if(empty($info)){
            return $this->return_false('你要修改的数据不存在！！');
        }

        // 模型 和 查询
        $course_id = $info->id;
        $studentDb = new CourseStudent();
        $cycleDb   = new CourseCycle();
        $info->fill($data);

        // 如果有周期 则删除，重新计算
        if($cycle){
            $cycleDb->where('course_id', $course_id)->delete();
        }


        // 保存信息
        DB::beginTransaction();
        try{
            // 保存
            $result = $info->save();

            // 保存学生
            if($student){
                $all = [];
                foreach($student as $item){
                    $all[] = ['course_id' => $course_id, 'student_id' => $item];
                }
                $studentDb->insert($all);
            }

            // 保存课程周期
            if($cycle){
                $all = [];
                foreach($cycle as $item){
                    $all[] = ['course_id' => $course_id, 'cycle' => $item['cycle'], 'number' => $item['number'], 'hour' => $item['hour'], 'minute' => $item['minute']];
                }
                $cycleDb->insert($all);
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($info, $data);

        return $this->id;
    }


    // 查询课程 同时查询周期 和 课程学生 上课时间
    public function oneFind($where, $order = "id DESC")
    {
        // 获取缓存
        $is_cache = $this->is_cache || $this->bang;
        $args     = compact('where', 'order');
        $info     = null;
        if($is_cache){
            $cacheName = $this->cacheKey('show', $args);
            $info      = $this->cacheClass()->getCache($cacheName);
            // 检查是否已经绑定
            if($info){
                $this->checkBangShow($info, $cacheName);
            }
        }
        // 查询
        if(empty($info)){
            //  查询
            $query = $this->where($where);
            if(is_array($order)){
            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $info = $query->first(); // ->recycle()
            if(empty($info)){
                return $this->return_false('数据不存在！！');
            }

            $info      = $info->toArray();
            $course_id = $info['id'];
            // 组合
            $info['cycle']     = (new CourseCycle())->where('course_id', $course_id)->get()->toArray();  // 查询周期
            $info['student']   = (new CourseStudent())->where('course_id', $course_id)->get()->toArray();   // 课程学生
            $info['all_times'] = (new CourseTimes())->where('course_id', $course_id)->get()->toArray();   // 上课时间

            // 保存为缓存
            if($is_cache){
                $this->addCacheShow($info, $cacheName, $info);
            }
        }

        // 编辑用户
        $info['user'] = [];
        if($info['uid']){
            $info['user'] = (new User())->isCache(true)->getOneById($info['uid']);
        }

        return $info;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'uid'        => 'required',
            'auth_id'    => 'required',
            'name'       => 'required',
            'times'      => 'required',
            'start_time' => 'required',
            'end_time'   => 'required',
            'status'     => ['in:-1,0,1,2'],
            //'city'        => 'required',
            //'address'     => 'required',
            //'description' => 'required',
        ];


        $msg = [
            'id'          => '自编号',
            'uid'         => '用户ID',
            'auth_id'     => '认证ID',
            'name'        => '认证名称',
            'times'       => '课时',
            'start_time'  => '开始时间',
            'end_time'    => '结束时间',
            'city'        => '城市',
            'address'     => '所在地',
            'description' => '认证描述',
            'status'      => '状态（1-正常，-1删除）',
            'ctime'       => '注册时间',
            'mtime'       => '更新时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
